#include "minieditwidget.h"
#include "ui_minieditwidget.h"

MiniEditWidget::MiniEditWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MiniEditWidget)
{
    ui->setupUi(this);

    lineEditList.insert("name", ui->name_lineEdit);
    lineEditList.insert("vorname", ui->vorname_lineEdit);
    lineEditList.insert("anschrift", ui->anschrift_lineEdit);
    lineEditList.insert("plz", ui->plz_lineEdit);
    lineEditList.insert("ort", ui->ort_lineEdit);
    lineEditList.insert("telefon", ui->telefon_lineEdit);
    lineEditList.insert("telefax", ui->telefax_lineEdit);
    lineEditList.insert("email", ui->email_lineEdit);

    foreach ( QLineEdit *le, lineEditList )
        connect(le, SIGNAL(textEdited(QString)), this, SIGNAL(dataChanged()));

    connect(this, SIGNAL(dataChanged()), this, SLOT(setDataChanged()));
    isDataChanged = false;
}

MiniEditWidget::~MiniEditWidget()
{
    delete ui;
}

bool MiniEditWidget::getDataChanged() const
{
    return isDataChanged;
}

void MiniEditWidget::clear()
{
    isDataChanged = false;
    currentId = -1;
    foreach ( QLineEdit *le, lineEditList )
        le->clear();
}

void MiniEditWidget::loadMini(int id)
{
    if ( Global::miniliste.contains(id) )
    {
        clear();
        currentId = id;

        MiniObject *m = Global::miniliste.value(id);
        ui->name_lineEdit->setText( m->getName() );
        ui->vorname_lineEdit->setText( m->getVorname() );
        ui->anschrift_lineEdit->setText(m->getAnschrift());
        ui->plz_lineEdit->setText(m->getPLZ());
        ui->ort_lineEdit->setText(m->getOrt());
        ui->telefon_lineEdit->setText(m->getTelefon());
        ui->telefax_lineEdit->setText(m->getTelefax());
        ui->email_lineEdit->setText(m->getEmail());
    }
}

void MiniEditWidget::setDataChanged()
{
    isDataChanged = true;
}

void MiniEditWidget::on_actionMinistrant_speichern_triggered()
{
    if ( ui->name_lineEdit->text().isEmpty() || ui->vorname_lineEdit->text().isEmpty() )
    {
        QMessageBox::information(this, tr("Ministrant speichern"), tr("Bitte geben Sie einen vollständigen Namen ein."), QMessageBox::Ok);
    }
    else
    {
        MiniObject *m = Global::miniliste.value(currentId);
        m->startTransaction();
        m->setName(ui->name_lineEdit->text());
        m->setVorname(ui->vorname_lineEdit->text());
        m->setAnschrift(ui->anschrift_lineEdit->text());
        m->setPLZ(ui->plz_lineEdit->text());
        m->setOrt(ui->ort_lineEdit->text());
        m->setTelefon(ui->telefon_lineEdit->text());
        m->setTelefax(ui->telefax_lineEdit->text());
        m->setEmail(ui->email_lineEdit->text());
        m->commitTransaction();
        isDataChanged = false;
    }
}

void MiniEditWidget::on_actionMinistrant_zuruecksetzen_triggered()
{
    foreach ( QLineEdit *le, lineEditList )
        while ( le->isUndoAvailable() )
            le->undo();
}
